# Create your views here.
from django.http import JsonResponse
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.views import APIView
from rest_framework_jwt.authentication import jwt_decode_handler, JSONWebTokenAuthentication

from ES_utils.es_utils import getClient, return_filter
from app.models import *
from app.utils import *
import json

# ---学者接口---
# 获取(GET)、修改(POST)学者个人信息
@method_decorator(csrf_exempt, name="dispatch")
class ScholarInfoView(APIView):

    def get(self, request):
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]

        if token is None:
            return JsonResponse({'msg': '获取学者个人信息', 'errno': 1001, 'errmsg': '无效的token'})

        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        user = User.objects.get(id=user_id)

        data = {"id": user_id, "realname": user.realname, "sex": user.sex, "email": user.email, "sign": user.sign,
                "field": user.field}

        return JsonResponse({'msg': '获取学者个人信息', 'errno': 0, 'errmsg': '成功', 'data': data})

    def post(self, request):
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]

        realname = request.POST.get("realname")
        sex = request.POST.get("sex")
        email = request.POST.get("email")
        sign = request.POST.get("sign")
        field = request.POST.get("field")

        if token is None:
            return JsonResponse({'msg': '修改学者个人信息', 'errno': 1001, 'errmsg': '无效的token'})

        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        user = User.objects.get(id=user_id)

        if realname is not None:
            user.realname = realname
        if sex is not None:
            user.sex = sex
        if email is not None:
            user.email = email
        if sign is not None:
            user.sign = sign
        if field is not None:
            user.field = field
        user.save()

        return JsonResponse({'msg': '修改学者个人信息', 'errno': 0, 'errmsg': '成功'})


# 获取其他学者个人信息
@method_decorator(csrf_exempt, name="dispatch")
class OtherScholarInfoView(APIView):

    def post(self, request):
        uid = request.POST.get("uid")
        if uid is None:
            return JsonResponse({'msg': '获取其他学者个人信息', 'errno': 1001, 'errmsg': '参数错误'})
        if User.objects.filter(id=uid) is None:
            return JsonResponse({'msg': '获取其他学者个人信息', 'errno': 1002, 'errmsg': '用户不存在'})
        user = User.objects.get(id=uid)
        Json_authorbody = {
            "query": {
                "match": {
                    "id": user.aid
                }
            }
        }
        client = getClient()
        if len(return_filter(client.search(index="author", body=Json_authorbody))) == 0:
            return JsonResponse({'msg': '获取其他学者个人信息', 'errno': 1002, 'errmsg': '不是学者'})
        author_response = return_filter(client.search(index="author", body=Json_authorbody))[0]
        author_response_json = json.loads(json.dumps(author_response))
        
        data = {
                "id": author_response_json["_source"].get("id"),
                "name": author_response_json["_source"].get("name"),
                "n_pubs": author_response_json["_source"].get("n_pubs"),
                "n_citation": author_response_json["_source"].get("n_citation")
                }


        return JsonResponse({'msg': '获取学者个人信息', 'errno': 0, 'errmsg': '成功',})


# 获取学者文献列表
@method_decorator(csrf_exempt, name="dispatch")
class ScholarPaperListView(APIView):

    def post(self, request):
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]

        if token is None:
            return JsonResponse({'msg': '获取学者文献列表', 'errno': 1001, 'errmsg': '无效的token'})

        user_id = request.POST.get("id")
        if user_id is '' or user_id is None:
            token_user = jwt_decode_handler(token)
            user_id = token_user['user_id']

        if User.objects.filter(id=user_id).count() <= 0:
            return JsonResponse({'msg': '获取学者文献列表', 'errno': 1004, 'errmsg': '获取用户失败'})

        user = User.objects.get(id=user_id)
        Json_authorbody = {
            "query": {
                "match": {
                    "id": user.aid
                }
            }
        }
        client = getClient()
        if len(return_filter(client.search(index="author", body=Json_authorbody))) == 0:
            return JsonResponse({'msg': '获取学者文献列表', 'errno': 1002, 'errmsg': '获取学者失败'})
        author_response = return_filter(client.search(index="author", body=Json_authorbody))[0]
        author_response_json = json.loads(json.dumps(author_response))
        author_id = author_response_json["_source"].get("id")
        # 获取相关论文信息
        Json_paperbody = {
            "query": {
                "match": {
                    "authors.id":author_id
                }
            }
        }
        client = getClient()
        if len(return_filter(client.search(index="author", body=Json_authorbody))) == 0:
            return JsonResponse({'msg': '获取学者文献列表', 'errno': 1003, 'errmsg': '获取论文失败'})
        paper_response = return_filter(client.search(index="paper", body=Json_paperbody))
        paper_response_json = json.loads(json.dumps(paper_response))

        paper_list = []
        author_id_list = []
        for paper_json in paper_response_json:
            authors = author_response_json["_source"].get("authors")
            for author in authors:
                author_id_list.append(author.get("id"))
            paper_list.append(
                {
                 'author': author_id_list,
                 'id': paper_json["_source"].get("id"),
                 'issue': paper_json["_source"].get("issue"),
                 'n_citation': paper_json["_source"].get("n_citation"),
                 'title': paper_json["_source"].get("title"),
                 'year': paper_json["_source"].get("year"),
                 'abstract': paper_json["_source"].get("abstract")
                 }
            )
            author_id_list = []
        # paper_list = sorted(paper_list, key=lambda x: x['year'])
        return JsonResponse({'msg': '获取学者文献列表', 'errno': 0, 'errmsg': '成功', 'data': paper_list})


# 获取学者关系
@method_decorator(csrf_exempt, name="dispatch")
class ScholarRelationView(APIView):

    def post(self, request):
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]

        if token is None:
            return JsonResponse({'msg': '获取学者关系', 'errno': 1001, 'errmsg': '无效的token'})

        user_id = request.POST.get("id")
        if user_id is '' or user_id is None:
            token_user = jwt_decode_handler(token)
            user_id = token_user['user_id']

        user = User.objects.get(id=user_id)
        Json_authorbody = {
            "query": {
                "match": {
                    "id": user.aid
                }
            }
        }
        client = getClient()
        if len(return_filter(client.search(index="author", body=Json_authorbody))) == 0:
            return JsonResponse({'msg': '获取学者文献列表', 'errno': 1002, 'errmsg': '获取学者失败'})
        author_response = return_filter(client.search(index="author", body=Json_authorbody))[0]
        author_response_json = json.loads(json.dumps(author_response))
        author_id = author_response_json["_source"].get("id")
        authors = []
        paper_id_list = []
        # 获取相关论文信息
        Json_paperbody = {
            "query": {
                "match": {
                    "authors.id":author_id
                }
            }
        }
        client = getClient()
        if len(return_filter(client.search(index="author", body=Json_authorbody))) == 0:
            return JsonResponse({'msg': '获取学者文献列表', 'errno': 1003, 'errmsg': '获取论文失败'})
        paper_response = return_filter(client.search(index="paper", body=Json_paperbody))
        paper_response_json = json.loads(json.dumps(paper_response))

        for paper_json in paper_response_json:
            paper_id_list.append(paper_json["_source"].get("id"))
            for author in paper_json["_source"].get("authors"):
                authors.append(author.get("id"))

        data = []
        for i in authors:
            if i == author_id:
                continue
            Json_authorbody = {
                "query": {
                    "match": {
                        "id": i
                    }
                }
            }
            client = getClient()
            author_response = return_filter(client.search(index="author", body=Json_authorbody))[0]
            author_response_json = json.loads(json.dumps(author_response))
            flag = 0
            for j in data:
                if j['name'] == author_response_json["_source"].get("name"):
                    flag = 1
                    j['value'] = j['value'] + 1
            if flag == 0:
                data.append({'id': i, 'name': author_response_json["_source"].get("name"), 'value': 1})

        return JsonResponse({'msg': '获取学者关系', 'errno': 0, 'errmsg': '成功', 'data': data})


# 取消认领文献
@method_decorator(csrf_exempt, name="dispatch")
class CancelPaperView(APIView):

    def post(self, request):
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]
        return JsonResponse({'msg': '此接口无效，请勿调用！', 'errno': 0, 'errmsg': '成功'})
'''
        if token is None:
            return JsonResponse({'msg': '取消认领文献', 'errno': 1001, 'errmsg': '无效的token'})

        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        user = User.objects.get(id=user_id)
        Json_authorbody = {
            "query": {
                "match": {
                    "id": user.aid
                }
            }
        }
        client = getClient()
        if len(return_filter(client.search(index="author", body=Json_authorbody))) == 0:
            return JsonResponse({'msg': '获取学者文献列表', 'errno': 1002, 'errmsg': '获取学者失败'})
        author_response = return_filter(client.search(index="author", body=Json_authorbody))[0]
        author_response_json = json.loads(json.dumps(author_response))
        author_id = author_response_json["_source"].get("id")

        pid = request.POST.get("pid")
        if pid is None:
            return JsonResponse({'msg': '取消认领文献', 'errno': 1003, 'errmsg': 'pid传参失败'})

        a2p = Author2Paper.objects.filter(aid=author_id, pid=pid)
        if a2p is None:
            return JsonResponse({'msg': '取消认领文献', 'errno': 1004, 'errmsg': '获取学者文献关系失败'})
        a2p.delete()
'''



# 发送邮件接口
@method_decorator(csrf_exempt, name="dispatch")
class SendEmailView(APIView):
    authentication_classes = []
    permission_classes = [AllowAny]

    def post(self, request):
        email = request.POST.get("email")
        send_type = request.POST.get("type")
        if email is None or send_type is None:
            return JsonResponse({'msg': '发送邮件接口', 'errno': 1001, 'errmsg': '参数错误'})

        # if Email.objects.filter(email=email).count() > 0:
        #    return JsonResponse({'msg': '发送邮件接口', 'errno': 1003, 'errmsg': '邮件已发送'})

        send_status = send_verification_code(email, send_type)

        if send_status == EmailSendStatusEnum.FAIL:
            return JsonResponse({'msg': '发送邮件接口', 'errno': 1003, 'errmsg': '发送邮件失败'})

        return JsonResponse({'msg': '发送邮件接口', 'errno': 0, 'errmsg': '成功'})


# 反馈文献缺失接口
@method_decorator(csrf_exempt, name="dispatch")
class FeedbackMissingPaper(APIView):

    def post(self, request):
        uid = request.POST.get("id")
        title = request.POST.get("title")
        author = request.POST.get("author")
        keyword = request.POST.get("keyword")
        date = request.POST.get("date")
        doi = request.POST.get("doi")
        abstract = request.POST.get("abstract")
        link = request.POST.get("link")
        print(uid, title, author, keyword, date, doi, abstract, link)
        if uid is None or title is None or author is None or keyword is None or date is None or doi is None or abstract is None or link is None:
            return JsonResponse({'msg': '反馈文献缺失接口', 'errno': 1001, 'errmsg': '参数错误'})

        user = User.objects.get(id=uid)

        missingpaper = Missingpaper()
        missingpaper.uid = user
        missingpaper.title = title
        missingpaper.author = author
        missingpaper.keyword = keyword
        missingpaper.date = date
        missingpaper.doi = doi
        missingpaper.abstract = abstract
        missingpaper.link = link
        missingpaper.save()

        return JsonResponse({'msg': '反馈文献缺失接口', 'errno': 0, 'errmsg': '成功'})
